﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeastSquares.Function
{
    /// <summary>
    /// 工具类，用于处理输入与输出
    /// </summary>
    internal class ReadNumberInTxt
    {
        /// <summary>
        /// 从指定路径的文件读取一系列值放入List<double>();
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<double> ReadListFromText(string path)
        {
            //判断文件是否存在
            if (File.Exists(path))
            {
                List<double> list = new List<double>();
                //存在关闭问题，using可以自动关闭using的变量，做内存回收
                using (TextReader tr = File.OpenText(path))
                {
                    string str = tr.ReadToEnd();
                    //split()方法主要用于将一个字符串分隔成多个字符串数组,这里为空格切割
                    var strs = str.Split(' ',StringSplitOptions.RemoveEmptyEntries);
                    list = strs.Select(m => double.Parse(m)).ToList();                                  
                    return list;
                }
            }
            else
                throw new Exception($"数据文件{path}不存在");
        }
    }
}
